﻿//设计模式 - 责任链模式
//目的：层层传递，层层处理


var context = new ProcessContext();
var manager = new ProcessA();
var leader = new ProcessB();
var director = new ProcessC();

leader.Next = director;
director.Next = manager;

leader.Process(context);





Console.ReadKey();

class ProcessContext
{
    public string Name { get; set; }
}

abstract class ProcessHandler
{
    public ProcessHandler Next { get; set; }

    public abstract void Process(ProcessContext context);
}

class ProcessA : ProcessHandler
{
    public override void Process(ProcessContext context)
    {
        //...

        context.Name = "领导";

        Console.WriteLine("流程 A,{0}处理", context.Name);
        Next?.Process(context);
    }
}

class ProcessB : ProcessHandler
{
    public override void Process(ProcessContext context)
    {
        context.Name = "主管处理";

        Console.WriteLine("流程 B,{0}处理", context.Name);
        Next?.Process(context);
    }
}


class ProcessC : ProcessHandler
{
    public override void Process(ProcessContext context)
    {
        context.Name = "总监处理";

        Console.WriteLine("流程 C,{0}处理", context.Name);
        Next?.Process(context);
    }
}






















































//var app = new ApplicationBuilder();

//app.Use((context, next) =>
//{
//    Console.WriteLine("Use 1");
//    return next();
//})
//    .Use((context, next) =>
//    {
//        Console.WriteLine("Use 2");
//        return next();
//    }).Build().Invoke(new());
class HttpContext
{

}


internal delegate Task RequestDelegate(HttpContext context);

class ApplicationBuilder
{
    static readonly List<Func<RequestDelegate, RequestDelegate>> _pipelines = new();
    public ApplicationBuilder Use(Func<HttpContext, Func<Task>, Task> middleware)
    {
        return Use(next =>
        {
            return context =>
            {
                Task SimpleNext() => next(context);
                return middleware(context, SimpleNext);
            };
        });
    }
    public ApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware)
    {
        _pipelines.Add(middleware);
        return this;
    }

    public RequestDelegate Build()
    {
        RequestDelegate app = context =>
        {
            Console.WriteLine("默认中间件");
            return Task.CompletedTask;
        };

        _pipelines.Reverse();
        foreach (var pipeline in _pipelines)
        {
            app = pipeline(app);
        }
        return app;
    }
}